package top.hyz.hrm.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.hyz.hrm.AjaxResult;
import top.hyz.hrm.AssertUtils;
import top.hyz.hrm.CourseDoc;
import top.hyz.hrm.ErrorCode;
import top.hyz.hrm.client.IFeignClient;
import top.hyz.hrm.constant.CourseConstant;
import top.hyz.hrm.domain.Course;
import top.hyz.hrm.domain.CourseDetail;
import top.hyz.hrm.domain.CourseMarket;
import top.hyz.hrm.domain.CourseType;
import top.hyz.hrm.dto.CourseDTO;
import top.hyz.hrm.dto.EmailDTO;
import top.hyz.hrm.dto.MessageDTO;
import top.hyz.hrm.exception.GlobalException;
import top.hyz.hrm.mapper.CourseDetailMapper;
import top.hyz.hrm.mapper.CourseMapper;
import top.hyz.hrm.mapper.CourseMarketMapper;
import top.hyz.hrm.mapper.CourseTypeMapper;
import top.hyz.hrm.service.ICourseService;

import java.util.Arrays;

import static top.hyz.hrm.constant.ThirdConstant.EXCHANGE_NAME_TOPIC;

/**
 * <p>
 * 课程服务Service层实现类
 * </p>
 *
 * @author Hanyuze
 * @since 2021-01-19
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private CourseDetailMapper courseDetailMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseTypeMapper courseTypeMapper;
    @Autowired
    private IFeignClient feignClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 添加/修改课程信息
     *
     * @param courseDto 传递的实体
     */
    @Override
    public void saveOrUpdate(CourseDTO courseDto) {
        Course course = courseDto.getCourse();
        CourseDetail courseDetail = courseDto.getCourseDetail();
        CourseMarket courseMarket = courseDto.getCourseMarket();

        if (course.getId() != null) {
            //修改
        } else {
            //新增
            save(course, courseDetail, courseMarket);
        }
    }

    /**
     * 添加课程信息
     *
     * @param course       课程对象
     * @param courseDetail 课程简介对象
     * @param courseMarket 课程价格对象
     */
    public void save(Course course, CourseDetail courseDetail, CourseMarket courseMarket) {

        //保存课程信息
        saveCourse(course);

        //保存课程简介信息
        saveCourseDetail(course, courseDetail, courseMarket);

        //课程类型的数量+1
        saveCourseType(course);
    }

    /**
     * 保存课程信息
     *
     * @param course 课程对象
     */
    private void saveCourse(Course course) {

        course.setTenantId(26L);
        course.setTenantName("源码时代");
        course.setUserId(42L);
        course.setUserName("yhptest");
        course.setStatus(0);
        course.setSaleCount(0);
        course.setViewCount(0);
        course.setCommentCount(0);
        baseMapper.insert(course);

    }

    /**
     * 保存课程详情信息
     *
     * @param course       课程对象
     * @param courseDetail 课程详情
     * @param courseMarket 课程售价
     */
    private void saveCourseDetail(Course course, CourseDetail courseDetail, CourseMarket courseMarket) {

        courseDetail.setId(course.getId());
        courseDetailMapper.insert(courseDetail);
        //保存课程价格信息
        courseMarket.setId(course.getId());
        courseMarketMapper.insert(courseMarket);

    }

    /**
     * 保存课程分类信息
     *
     * @param course 课程对象
     */
    private void saveCourseType(Course course) {

        CourseType courseType = courseTypeMapper.selectById(course.getCourseTypeId());
        courseType.setTotalCount(courseType.getTotalCount() + 1);
        courseTypeMapper.updateById(courseType);

    }


    /**
     * 课程发布
     *
     * @param id 课程编号
     */
    @Override
    public void onLineCourse(Long id) {
        //校验id是否为空
        AssertUtils.isNotEmpty(id, ErrorCode.COURSE_ID_NOT_EMPTY_401);

        //查询课程信息
        Course course = baseMapper.selectById(id);

        //校验查询结果是否为空
        AssertUtils.isNotEmpty(course, ErrorCode.COURSE_NOT_EMPTY_402);

        //校验课程状态是否为已下线状态
        if (course.getStatus().equals(CourseConstant.COURSE_STATUS_ONLINE)) {
            throw new GlobalException(CourseConstant.REPEATED_COURSES_MESSAGE);
        }
        //修改课程状态
        course.setStatus(CourseConstant.COURSE_STATUS_ONLINE);
        //保存修改后的课程信息
        baseMapper.updateById(course);

        //查询课程详情信息
        CourseDetail courseDetail = courseDetailMapper.selectById(course.getId());
        //查询课程价格信息
        CourseMarket courseMarket = courseMarketMapper.selectById(course.getId());
        //查询课程分类信息
        CourseType courseType = courseTypeMapper.selectById(course.getCourseTypeId());

        //准备保存到ES中的对象
        CourseDoc courseDoc = new CourseDoc();
        BeanUtils.copyProperties(course, courseDoc);
        BeanUtils.copyProperties(courseDetail, courseDoc);
        BeanUtils.copyProperties(courseMarket, courseDoc);
        courseDoc.setCharge(courseMarket.getCharge() == 1 ? "免费" : "收费");
        courseDoc.setCourseTypeId(courseType.getId());
        courseDoc.setCourseTypeName(courseType.getName());
        courseDoc.setSearchField(course.getName() + courseDetail.getIntro());

        //保存到ES中，判断保存结果并响应给前端
        AjaxResult ajaxResult = feignClient.onLineCourse(courseDoc);
        if(!ajaxResult.isSuccess()){
            throw new GlobalException("课程上线遇到故障，请稍后再试");
        }


        //课程发布消息推送
        //1.手机短信推送
        publishMessage(courseDoc);
        //2.邮件推送
        publishEmail(courseDoc);
    }

    /**
     * 推送手机短信
     * @param courseDoc
     */
    public void publishMessage(CourseDoc courseDoc){
        //准备短信对象
        MessageDTO message = new MessageDTO();
        String content = "尊敬的%s先生，您订阅的%s机构的%s课程已上线，点击<a href='https://www.baidu.com/id=%s'>链接</a>即可观看";
        message.setPhones(Arrays.asList("17602325042", "13798803989"));
        content = String.format(content, "韩雨泽", courseDoc.getTenantName(), courseDoc.getName(), courseDoc.getId());
        message.setContent(content);

        //发布到mq中
        rabbitTemplate.convertAndSend(EXCHANGE_NAME_TOPIC, "message.sms", message);
    }

    /**
     * 推送邮件
     * @param courseDoc
     */
    public void publishEmail(CourseDoc courseDoc){
        //准备邮件
        EmailDTO email = new EmailDTO();
        String content = "尊敬的%s先生，您订阅的%s机构的%s课程已上线，点击<a href='https://www.baidu.com/id=%s'>链接</a>即可观看";
        content = String.format(content , "韩雨泽", courseDoc.getTenantName(), courseDoc.getName(), courseDoc.getId());
        email.setUrl(Arrays.asList("a@qq.com", "b@qq.com"));
        email.setContent(content);

        //发布到mq中
        rabbitTemplate.convertAndSend(EXCHANGE_NAME_TOPIC, "message.email", email);
    }
}
